import os
import subprocess

def transcode_video_for_recording(input_path, output_path):
    """
    为录制效果转码视频

    Args:
        input_path (str): 输入视频路径
        output_path (str): 输出视频路径
    """
    try:
        cmd = [
            'ffmpeg',
            '-i', input_path,
            '-vf', 'setpts=PTS+0.05/TB,eq=brightness=0.02:contrast=1.03,boxblur=1:1',
            '-af', 'atempo=1.0',
            '-c:v', 'libx264',
            '-preset', 'medium',
            '-crf', '23',
            '-c:a', 'aac',
            '-b:a', '128k',
            '-movflags', '+faststart',
            '-map_metadata', '-1',
            '-y',
            output_path
        ]

        print(f"正在转码视频: {input_path}")
        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')

        if result.returncode == 0:
            print(f"视频转码成功: {output_path}")
            return True
        else:
            print(f"视频转码失败: {input_path}\n{result.stderr}")
            return False
    except Exception as e:
        print(f"视频转码时出错: {input_path}\n{str(e)}")
        return False


def batch_transcode_folder(input_dir, output_dir=None):
    """
    批量转码文件夹下所有视频文件

    Args:
        input_dir (str): 输入视频文件夹路径
        output_dir (str|None): 输出视频文件夹路径，如果为None则覆盖原文件
    """
    video_extensions = ('.mp4', '.mov', '.mkv', '.avi', '.flv', '.wmv')

    if not os.path.exists(input_dir):
        print(f"输入目录不存在: {input_dir}")
        return

    if output_dir:
        os.makedirs(output_dir, exist_ok=True)
    else:
        output_dir = input_dir  # 覆盖原文件

    for root, dirs, files in os.walk(input_dir):
        for filename in files:
            if not filename.lower().endswith(video_extensions):
                continue

            input_path = os.path.join(root, filename)

            if output_dir == input_dir:
                # 先转码到临时文件，转码成功再替换原文件
                temp_output = input_path + ".tmp.mp4"
                success = transcode_video_for_recording(input_path, temp_output)
                if success:
                    os.replace(temp_output, input_path)
            else:
                # 输出到指定文件夹
                rel_path = os.path.relpath(root, input_dir)
                target_dir = os.path.join(output_dir, rel_path)
                os.makedirs(target_dir, exist_ok=True)
                output_path = os.path.join(target_dir, filename)
                transcode_video_for_recording(input_path, output_path)


if __name__ == "__main__":
    input_folder = r"\\Fw-152\e\媒体部素材\搬运测试\20251017\搬运"
    output_folder = None # 可以设为None覆盖原文件

    batch_transcode_folder(input_folder, output_folder)
